import React, { useState, useEffect, useRef } from 'react';
import { Button, Dropdown, Space } from 'antd';
import '../../style/main.css';
import '../../style/kuangjia.css';

const MusicPlayer = ({ currentSong }) => {
  const audioRef = useRef(null); // 引用音频元素
  const [isPlaying, setIsPlaying] = useState(false); // 音乐是否在播放
  const [progress, setProgress] = useState(0); // 进度条的值
  const [currentTime, setCurrentTime] = useState(0); // 当前播放时间
  const [duration, setDuration] = useState(0); // 音乐总时长
  // 格式化秒数为 "分钟:秒"
  const formatDuration = (duration) => {
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  // 格式化毫秒为 "分钟:秒"
  const formatDuration2 = (durationInMilliseconds) => {
    const durationInSeconds = Math.floor(durationInMilliseconds / 1000);
    const minutes = Math.floor(durationInSeconds / 60);
    const seconds = Math.floor(durationInSeconds % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
  };

  const items = [
    {
      key: '1',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
          收藏
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
          下载
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          添加到歌单
        </a>
      ),
    },
  ];

  // 播放/暂停切换
  const togglePlayPause = () => {
    const audio = audioRef.current;
    if (isPlaying) {
      audio.pause();
    } else {
      audio.play();
    }
    setIsPlaying(!isPlaying);
  };


  useEffect(() => {
    const audio = audioRef.current;
    let interval;

    if (audio) {
      audio.src = currentSong?.playUrl || '';
      audio.load();
      setDuration(audio.duration); // 获取音频总时长

      // 每100ms更新一次进度条和播放时间
      interval = setInterval(() => {
        setCurrentTime(audio.currentTime);
        setProgress((audio.currentTime / audio.duration) * 100); // 更新进度条
      }, 100);

      return () => clearInterval(interval);
    }
  }, [currentSong]); // 每次更换歌曲时都会触发

  return (
    <div className="buttom">
      <audio
        ref={audioRef}
        preload="auto"
      />
      <div className="start">
        <div className="music-small-img">
          <a href="#">
            <img id="playsongImg" src={currentSong.albumPic} alt="music-logo" />
          </a>
        </div>
        <div className="music-information">
          <ul>
            <li id="playsongname">{currentSong.name}</li>
            <li id="playsinger">{currentSong.singer}</li>
          </ul>
        </div>
        <div className="selections">
          <p>
            <i className="ri-heart-3-line"></i>
            <i className="ri-message-3-line"></i>

            <Space direction="vertical">
              <Space wrap>
                <Dropdown
                  menu={{
                    items,
                  }}
                  placement="topLeft"
                >
                  <i className="ri-menu-2-fill"></i>
                </Dropdown>
              </Space>
            </Space>
          </p>
        </div>
      </div>

      <div className="center">
        <div className="mediaControl">
          <ul>
            <li><i className="ri-skip-back-fill"></i></li>
            <li>
              <i
                onClick={togglePlayPause}
                id="play_pause"
                className={isPlaying ? "ri-pause-line" : "ri-play-fill"}
              ></i>
            </li>
            <li><i className="ri-skip-forward-fill"></i></li>
          </ul>
        </div>

        {/* 进度条部分 */}
        <div className="mediaprogress">
          <span id="currenttime">{formatDuration(currentTime)}</span>
          <input
            type="range"
            value={progress}
            className="progress-bar"
            style={{
              background: `linear-gradient(to right, #4CAF50 ${progress}%, #ddd ${progress}%)`, // 动态更新进度条颜色
            }}
          />
          <span id="totaltime">{formatDuration2(currentSong.duration)}</span>
        </div>
      </div>
      <div className="end">wohenhao</div>
    </div>
  );
};

export default MusicPlayer;
